package purchaseOrder

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/apps/purchase/auth"
	"insighttracking/common/utils"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchaseOrderDetailApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchaseOrderDetailApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchaseOrderDetailApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchaseOrderDetailApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchaseOrderDetailApiLogic) GetPurchaseOrderDetailApi(req *types.IdReq) (resp *types.GetPurchaseOrderDetailResp, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	orderPageRespBo, err := service.PurchaseOrderService.GetPurchaseOrderByIdApi(l.ctx, accountInfo.EnterpriseId, req.Id)
	if err != nil || orderPageRespBo == nil {
		return nil, errors.New("查询失败")
	}

	var dataList = make([]types.PurchaseOrdersDetailModel, 0)
	detailEntities, err := service.PurchaseOrderDetailService.GetByPurchaseOrderIdApi(l.ctx, []int64{req.Id})
	if err == nil && len(detailEntities) > 0 {
		// 呼气采购计划信息
		purchasePlanIdList := k.Map(detailEntities, func(item *model.PurchaseOrdersDetailEntity, index int) int64 {
			return item.PurchasePlanID
		})
		planEntities, err := service.PurchasePlanService.GetByIdListApi(l.ctx, k.Distinct(purchasePlanIdList), []int64{})
		var planOrderNoMap = make(map[int64]string)
		if err == nil && len(planEntities) > 0 {
			planOrderNoMap = k.ToMap(planEntities, func(item *model.PurchasePlanEntity) (int64, string) {
				return item.ID, item.OrderNo
			})
		}
		// 获取采购入库信息
		purchaseStoreEntity, err := service.PurchaseStoreService.GetPurchaseStoreByPurchaseOrderIdApi(l.ctx, req.Id)
		var spuIdMap = make(map[int64]*model.PurchaseStoreDetailEntity)
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			// 获取入库详情信息
			purchaseStoreDetailEntity, err1 := service.PurchaseStoreDetailService.GetPurchaseStoreByParentIdApi(l.ctx, purchaseStoreEntity.ID)
			if err1 == nil && len(purchaseStoreDetailEntity) > 0 {
				spuIdMap = k.ToMap(purchaseStoreDetailEntity, func(item *model.PurchaseStoreDetailEntity) (int64, *model.PurchaseStoreDetailEntity) {
					return item.SpuID, item
				})
			}
		}
		// 入库详情
		for _, item := range detailEntities {
			purchasePlanOrderNo, isOk := planOrderNoMap[item.PurchasePlanID]
			storeDetailEntities, isOk1 := spuIdMap[item.SpuID]
			detailModel := types.PurchaseOrdersDetailModel{
				ID:                      item.ID,                             // 主键id
				PurchasePlanID:          item.PurchasePlanID,                 // 采购计划表purchase_plan主键id,如果pc创建的采购单这里为空
				PurchasePlanOrderNo:     k.If(isOk, purchasePlanOrderNo, ""), // 采购计划表purchase_plan主键id,如果pc创建的采购单这里为空
				PurchaseOrdersID:        item.PurchaseOrdersID,               // 采购单purchase_orders表主键id
				SpuID:                   item.SpuID,                          // 商品,关联到spu表主键id
				SnapshotSpuName:         item.SnapshotSpuName,                // '快照商品名称
				SnapshotProductImageURL: item.SnapshotProductImageURL,        // 快照产品图片
				SnapshotSpuType:         item.SnapshotSpuType,                // 快照商品类型,0表示基础商品,1表示加工商品
				SnapshotUnit:            item.SnapshotUnit,                   // 快照单位
				SnapshotCategoryID:      item.SnapshotCategoryID,             // 快照分类id
				SnapshotCategory:        item.SnapshotCategory,               // 快照分类
				SnapshotPrice:           item.SnapshotPrice.StringFixed(2),   // 快照商品单价
				LossRate:                item.LossRate.StringFixed(2),        // 快照损耗率
				PurchaserPrice:          item.PurchaserPrice.StringFixed(2),  // 采购单价
				PurchaserCount:          item.PurchaserCount.StringFixed(2),  // 采购数量
				PurchaserAmount:         item.PurchaserAmount.StringFixed(2), // 采购金额
				StoreStatus:             item.StoreStatus,                    // 入库状态,-1表示取消,0表示待入库,10表示已入库,20表示退货
				Remark:                  item.Remark,                         // 备注
				InStoreDate:             0,                                   // 入库时间
				InStoreCount:            decimal.Zero.StringFixed(2),         // 已入库数量
			}
			if isOk1 {
				detailModel.InStoreDate = utils.TimestampToString(storeDetailEntities.CreatedAt)
				detailModel.InStoreCount = storeDetailEntities.StoreCount.StringFixed(2)
			}
			dataList = append(dataList, detailModel)
		}
	}
	return &types.GetPurchaseOrderDetailResp{
		DataList: dataList,
	}, nil
}
